package com.zys.utils;

import java.io.*;

/**
 * 序列化工具类
 */
public class SerializeUtils {

  /**
   * 序列化
   *
   * @param object 序列化对象
   * @return 序列化对象的字节数组
   * @throws Exception IOException
   */
  public static byte[] serialize(Object object) throws Exception {
    // 字节输出流
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    // 对象输出流
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(object);

    return byteArrayOutputStream.toByteArray();
  }

  /**
   * 反序列化
   *
   * @param bytes 对象序列化后的字节数组
   * @return 原对象
   * @throws Exception IOException ClassNotFoundException
   */
  public static Object deserialize(byte[] bytes) throws Exception {
    // 字节输入流
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    // 对象输入流
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

    return objectInputStream.readObject();
  }
}
